package com.xz.util.openplatform;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;
import java.util.TimeZone;

public final class DateTimeUtils {


    /**
     * 获取UnixTime时间精度
     *
     * @return
     */
    public static LocalDateTime ToUnixTimePrecision(LocalDateTime time) {
        return of((getTime(time) / Precision) * Precision);
    }

    private static final long Precision = 1000L;

    /**
     * 获取TimeStamp
     *
     * @return
     */
    public static long GetUnixTimeStamp() {
        return ToUnixTime(LocalDateTime.now());
    }

    /**
     * 从Unix时间获取时间
     *
     * @param timeStamp
     * @return
     */
    public static LocalDateTime GetUTCTimeFromUnixTimeStamp(long timeStamp) {
        return of(getTime(UnixStartTime) + timeStamp * Precision);
    }

    /**
     * 获取Unix时间,相当于 System.currentTimeMillis()方法。
     *
     * @param time
     * @return
     */
    public static long ToUnixTime(LocalDateTime time) {
        LocalDateTime utc=convertToUtc(time);
        LocalDateTime firstUtc=UnixStartTime;
        return  (getTime(utc) -getTime( firstUtc)) / Precision;
    }

    private static final LocalDateTime UnixStartTime = LocalDateTime.of(1970, 1,
            1, 0, 0, 0); //Unix起始时间


    private  static long getTime(LocalDateTime time)
    {
        return   time.toInstant(ZoneOffset.UTC).toEpochMilli();
    }

    private  static  LocalDateTime of(long ticks)
    {
        return  LocalDateTime.ofInstant( Instant.ofEpochMilli(ticks),ZoneOffset.UTC);

    }

    public static  LocalDateTime convertToUtc(LocalDateTime time) {

        return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
    }
}
